package nero.yncc.com.createart.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.HashMap;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.base.BaseActivity;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.UserBean;
import nero.yncc.com.createart.utils.HttpUtils;
import nero.yncc.com.createart.utils.UserDataUtil;

/**
 * Created by nero on 17-6-20.
 */

@ContentView(R.layout.activity_login_account_phone)
public class ActivityAccountOrPhoneLogin extends BaseActivity {

    @ViewInject(R.id.et_account)
    EditText et_account;

    @ViewInject(R.id.et_password)
    EditText et_password;

    @ViewInject(R.id.btn_login)
    TextView btn_login;

    String account, password; //登录用户名和密码

    @Override
    protected void initView() {
        super.initView();
        setTitleBarTitle("登录");

    }

    @Override
    protected void initListener() {
        super.initListener();
        btn_login.setOnClickListener(this);
    }

    @Override
    protected void doClick(int id) {
        super.doClick(id);
        switch (id) {
            case R.id.btn_login:

                login();
                break;
        }
    }

    private void login() {

        if (!checkLogin()) return;
        showProgress("正在登录");
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("username", account);
        hashMap.put("password", password);

        new HttpUtils().post(this, Constants.API_LOGIN, hashMap, UserBean.class, HttpUtils.TYPE_OBJECT, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                UserBean userBean = (UserBean) json;
                UserDataUtil.saveUserData(mContext, userBean);  //保存用户数据
                hideProgress();
                Intent intent = new Intent(mContext, ActivityIndex.class);
                startActivity(intent);
            }

            @Override
            public void fail(String failMsg) {
                showToast(failMsg);
                hideProgress();
            }
        });
    }

    /**
     * 检查登录是否合法
     *
     * @return 返回true合法 返回false非法
     */
    private boolean checkLogin() {
        account = et_account.getText().toString();
        password = et_password.getText().toString();

        if (TextUtils.isEmpty(account)) {
            showToast("请输入用户名");
            return false;
        }

        if (TextUtils.isEmpty(password)) {
            showToast("请输入密码");
            return false;
        }

        return true;
    }
}
